package com.naiterui.ehp.bs.cms.common.json;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.naiterui.ehp.bs.cms.modules.sys.utils.DictUtil;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;

/**
 * 字典过滤
 *
 * @author 王泽浩
 * @date 2019-02-19 14:14
 * @since 1.0.0
 */
@Slf4j
public class DictFieldSerializer extends StdSerializer<Object> implements ContextualSerializer {

    private static final long serialVersionUID = -6171864107747220506L;

    private Dict dict;

    private String field;

    @SuppressWarnings("unused")
    public DictFieldSerializer() {
        super(Object.class);
    }

    private DictFieldSerializer(String field, Dict dict) {
        super(Object.class);
        this.field = field;
        this.dict = dict;
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) {
        Dict dict = property.getAnnotation(Dict.class);
        if (dict != null) {
            return new DictFieldSerializer(property.getName(), dict);
        }
        return null;
    }

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeObject(value);
        String fieldName = this.field + "Describe";
        if (value == null) {
            gen.writeStringField(fieldName, null);
            return;
        }
        String type = this.dict.type();
        String dictValue = DictUtil.getNameByTypeAndCode(type, value + "");
        gen.writeStringField(fieldName, dictValue);

    }
}
